The Transition Effect
The JSFL for the Transition effect is contained in a file called UberTemplate2.jsfl. Structurally, the Transition effect isn't terribly different than the Drop Shadow; it just has more parameters—OK, a lot more! Look at this forward function:
function forward( preview, dur, xmode, xpos, ymode, ypos,
xscalemode, xscale, yscalemode, yscale,
anglemode, angle, colormode, color, easing,
direction, changealpha, alpha, fade, wipe, fly)
Wow, 21 parameters! It makes sense, though: There are more settings so there must be more parameters. If you compare this list to the actual effect, however, it seems that some of these settings are not implemented. A quick check of Transform.xml (the XML file for the Transition effect) tells you that it also uses UberTemplate2.jsfl for its code. A-ha! That explains the funny name—über, of course, being German for "one file used by two effects."
Look closely at the editor and see which parameter you actually need:
- dur: Effect's duration in the editor, measured in frames
- fade: In, out, or none—fades your selection in or out
- easing: Ranges from –100 to +100, just as in Flash
- wipe: In, out, or none—used as a mask to simulate a camera wipe
- direction: Direction of the wipe (up, down, right, left)
- preview: Used from the SWF editor when you click the Preview button
Über cool—that should make your life simpler here! Now let's figure out what you have to do. One of the difficulties here is that you will only use part of the source code, so a clear list is most helpful here:
- Save information about the current frame and total frames in the layer; a symbol affects the final length of this frame, while a movie clip does not.
- Enter the effect symbol, create a symbol from the selection, and make sure it is all nice in the library.
- Add the appropriate number of key frames to hold the whole effect (the duration).
- Set either the first or the last frame's instance to the alpha value, depending on fade-in or fade-out.
- Set frame 0 to tween, also the easing amount here.
- If there is a wipe, insert a mask layer, add a box to it, and make sure it is the size of your symbol.
- Tween the box from the appropriate direction to the center, based on the user-chosen direction. (This will be the opposite if the direction is "in.")
- Adjust the number of frames if needed: a movie clip requires only one, while a symbol requires the full duration.
- Generate a preview if needed.
Let's trip now through the forward function, or at least the über relevant parts. First up, the regular suspects: enableImmediateUpdates (still on), load the shared library, and some shorthand:
fl.enableImmediateUpdates( true );
fl.runScript(fl.configURI + "Effects/shared.jsfl");
var myMainDoc = fl.getDocumentDOM();
var myMainTL = myMainDoc.getTimeline();
The start frame and duration is recorded so that you can adjust the main Timeline length later, if needed. The startFrame property gives the starting frame in case the selected frame is not a keyframe. The current selection/frame/layer is also stored. Whole bunch of stuff:
var frameNum = fl.getDocumentDOM().getTimeline().currentFrame;
var myCurrentFrame = myMainTL.layers[myMainTL.currentLayer].frames[myMainTL.currentFrame];
var startFrame = myCurrentFrame.startFrame;
var durationFrames = myCurrentFrame.duration;
var selectObj = fl.getDocumentDOM().selection;
var theEffectObj = selectObj[0];
var theCurrentFrameNum = fl.getDocumentDOM().getTimeline().currentFrame;
var theCurrentLayer = fl.getDocumentDOM().getTimeline().currentLayer;
Next, the Timeline (the main one, not inside the symbol) is extended, if needed, to handle the full duration of the effect. This is later trimmed if the symbol is a movie clip. While this may seem like an awkward process, it makes more sense when you take into account the transform usages, where the Timeline motion is a fair bit more complex. The selection is reset (this is a library utility) after this, to ensure that it is still pointing at the original selection:
var nToInsert = dur - durationFrames;
if (nToInsert > 0)
{
fl.getDocumentDOM().getTimeline().insertFrames(nToInsert, false);
}
Object.fxutil.resetSelection( theEffectObj, theCurrentFrameNum, theCurrentLayer );
Here is some code to get the bounds of your selection. This is used to create a mask of the same size for the wipes. It may seem long but basically it loops over all the objects and tries to find the most extreme positions. All the 9s are just another way of saying Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY:
var selXMin = 9999999999;
var selXMax = -99999999999;
var selYMin = 999999999999;
var selYMax = -99999999999;
var j;
var tx, ty;
var selectObj = fl.getDocumentDOM().selection;
var numFramesForEffect = dur - 1;
for (j = 0; j < selectObj.length; j++)
{
tx = 0;
ty = 0;
if ((selectObj[j].top + ty) < selYMin)
selYMin = selectObj[j].top + tx;
if ((selectObj[j].left + tx) < selXMin)
selXMin = selectObj[j].left + tx;
if ((selectObj[j].top + selectObj[j].height + ty) > selYMax)
selYMax = (selectObj[j].top + selectObj[j].height + ty);
if ((selectObj[j].left + selectObj[j].width + tx) > selXMax)
selXMax = (selectObj[j].left + selectObj[j].width + tx);
}
Last thing to save is the view matrix. If the symbol is rotated and scaled, your wipe mask will also have to be:
var viewMat = fl.getDocumentDOM().viewMatrix;
Now you can enter the symbol and create a new one to apply the effects to. Again, peace is made with the user's library. This is just like the Drop Shadow effect, except that the library utility isn't used this time:
fl.getDocumentDOM().enterEditMode("inPlace");
selectObj = fl.getDocumentDOM().selection;
// find a safe name for the library item
var cur_lib = fl.getDocumentDOM().library;
var libFolderName = Object.fxutil.getEffectsFolderName();
// create the folder if necessary
if (!cur_lib.itemExists(libFolderName) )
{
cur_lib.newFolder(libFolderName);
}
// create the item and move it to the folder
libName = Object.fxutil.generateLibName();
newMc = fl.getDocumentDOM().convertToSymbol("graphic", libName, "center");
cur_lib.moveToFolder(libFolderName, libName);
OK, ready to begin the real work, starting with some shorthand symbols. Whoops, here it says "doc" instead of "dom"—but, really, all the other effects are very good at keeping their naming consistent. (Perhaps this was the first effect written, or maybe it just means it doesn't matter that much after all.)
var doc = fl.getDocumentDOM();
var tl = doc.getTimeline();
Stretch your inner Timeline to match the effect's duration. You have one frame already, so you don't need to add that; hence the "– 1":
var numFramesForEffect = dur - 1;
tl.convertToKeyframes(numFramesForEffect);
If you set the duration to 0 or 1, you end up with an JSFL error here. The minimum duration probably should have been set to two frames. Oh well, no biggie. Note how the frames are converted to key frames, meaning the last frame will be a keyframe. This allows you to set the end properties of the tween on the final frame's symbol.
Go through the properties you have to adjust, starting with "alpha." Notice how the way these are set depends on whether they are fading in or out (they remain unset if they aren't fading at all, of course):
if (fade != "none" )
{
if (fade == "out")
{
var instance2 = tl.layers[0].frames[numFramesForEffect].elements[0];
instance2.colorAlphaPercent = 0;
}
else
{
var instance2 = tl.layers[0].frames[0].elements[0];
instance2.colorAlphaPercent = 0;
}
}
Now you can do the easing while creating the tween. The tween is created on frame 0 (all arrays are zero-based here) because that is where it starts. The variable easing is from the editor:
tl.setFrameProperty('tweenType', 'motion', 0);
tl.setFrameProperty('tweenEasing', easing, 0);
The most complex part is creating the easing. It's not that any one part is hard, it's just that it takes so many steps that it can seem a bit overwhelming. It is probably large enough to warrant a list of steps again:
- Add a mask layer.
- Create a rectangle using the measurements from your symbol.
- Select it and create a library-friendly symbol.
- Determine where it should start and end, based on the wipe direction (and in versus out).
- Set the original layer to be masked by this layer.
Hopefully this seems simple enough. Each step isn't all that hard. Remember, you can always use the History panel to get JSFL clues. There is also the magnificent Flash JavaScript Dictionary (Adobe PDF); it's a very well made piece of documentation.
Add a layer above the current one and select it (the code checks whether all of this is necessary first—which it isn't if there is no wipe):
if (wipe != "none")
{
var maskLayerIndex = tl.addNewLayer();
tl.setSelectedLayers(maskLayerIndex);
tl.currentLayer = maskLayerIndex;
tl.currentFrame = 0;
Figure out how big your rectangle mask needs to be and then create it. The earlier bound measurements come in real handy here:
var maskWidth = selXMax - selXMin;
var maskHeight = selYMax - selYMin;
var maskLeftPos = 500;
var maskTopPos = 500;
fl.getDocumentDOM().addNewRectangle(
{ left:maskLeftPos,
top:maskTopPos,
right:maskLeftPos + maskWidth,
bottom:maskTopPos + maskHeight
}, 0);
This must be a symbol in the library, so select it first and then make it so. This gets easier when you know that the folders have been created already:
tl.setSelectedFrames([maskLayerIndex, 0, 1], true);
fl.getDocumentDOM().setSelectionRect(
{ left:maskLeftPos,
top:maskTopPos,
right:maskLeftPos + maskWidth,
bottom:maskTopPos + maskHeight
});
libName = Object.fxutil.generateLibName();
var myLocalVC = fl.getDocumentDOM().convertToSymbol("graphic", libName, "top left");
cur_lib.moveToFolder(libFolderName, myLocalVC.name);
To figure out where to put this, take into account that the symbol might have been transformed (scaled, rotated, and so on), so multiply your top-left corner by the matrix to get the result position:
var xLocal = selXMin*viewMat.a + selYMin*viewMat.c + viewMat.tx;
var yLocal = selXMin*viewMat.b + selYMin*viewMat.d + viewMat.ty;
Finally, move it into place:
fl.getDocumentDOM().moveSelectionBy({x:(-maskLeftPos), y: (-maskTopPos)});
fl.getDocumentDOM().moveSelectionBy({x:xLocal, y: yLocal});
Figure out where the wipe should start and end. This is based on two things: the direction (up, down, right, left) and whether to wipe in or out. Cue ferocious drumming ... ahhhhhh wipe-out! (If you aren't old enough to remember, that reference might have no meaning to you.)
var wipeX, wipeY;
if (direction == "Wipe Up")
{
wipeX = 0;
wipeY = maskHeight;
if (wipe == "out")
wipeY = -wipeY;
}
if (direction == "Wipe Down")
{
wipeX = 0;
wipeY = -maskHeight;
if (wipe == "out")
wipeY = -wipeY;
}
if (direction == "Wipe Right")
{
wipeX = -maskWidth;
wipeY = 0;
if (wipe == "out")
wipeX = -wipeX;
}
if (direction == "Wipe Left")
{
wipeX = maskWidth;
wipeY = 0;
if (wipe == "out")
wipeX = -wipeX;
}
if (wipe == "out")
fl.getDocumentDOM().moveSelectionBy({x:wipeX, y:wipeY});
Whew, getting very close to being done here. You now create the tween by adding the appropriate number of key frames and then moving the rectangle symbol on the last frame to where it needs to be if you are wiping in. If you are wiping out this will be on exactly the opposite side:
tl.convertToKeyframes(numFramesForEffect);
tl.setFrameProperty('tweenType', 'motion', 0);
tl.currentFrame = numFramesForEffect;
tl.setSelectedLayers(maskLayerIndex);
tl.currentLayer = maskLayerIndex;
// handle wipe in vs. wipe out
tl.setSelectedFrames([maskLayerIndex, 0, numFramesForEffect], true);
if (wipe == "out")
fl.getDocumentDOM().moveSelectionBy({x:-wipeX, y:-wipeY});
else
fl.getDocumentDOM().moveSelectionBy({x:wipeX, y:wipeY});
Last thing to do is set this to be a mask layer, called "MASK," and be sure the layer under it is actually being masked:
// set the layer type to mask at the end
tl.setLayerProperty("layerType", "mask");
tl.setLayerProperty("name", "MASK");
// set the current layer to be masked
tl.setSelectedLayers(maskLayerIndex + 1);
tl.setLayerProperty("layerType", "masked");
There you go, the wipe is done! If you look way back, you see that you are almost done with the whole effect. Deselect everything, set the current frame back to 0, and exit Edit mode:
tl.currentFrame = 0;
doc.selectNone();
fl.getDocumentDOM().exitEditMode();
Check whether the main Timeline has too many frames, based on what kind of symbol it was (a movie clip didn't need any extra frames):
// get the library item for the top level element var selectObj = fl.getDocumentDOM().selection; var libItem = selectObj[0].libraryItem; if (libItem.itemType == "movie clip") { var removeStart = startFrame + durationFrames; var removeEnd = startFrame + myCurrentFrame.duration; if (removeEnd > removeStart) { fl.getDocumentDOM().getTimeline().removeFrames(removeStart, removeEnd); var layerIndex = fl.getDocumentDOM().getTimeline().currentLayer; fl.getDocumentDOM().getTimeline().setSelectedFrames([layerIndex, startFrame, startFrame+1], true); } }
Put the current frame back to where it was when you started. Basically, everything will be set back to how it was, except for a few frames that might be holding the effect:
if (fade == "in" || wipe == "in")
frameNum = frameNum + dur - 1;
fl.getDocumentDOM().getTimeline().currentFrame = frameNum;
Last thing: Just as with Drop Shadow, check if a preview needs to be generated. You do this with the utility library:
if (preview)
{
Object.fxutil.exportPreviewSWF( fl.getDocumentDOM().selection[0] );
}
Now you're done!
Removing the Transition Effect
Thankfully, reversing the Transition effect is much quicker that creating it. This is much like Drop Shadow's reverse: You aren't really unwinding what you did but destroying the evidence. Just as with the forward code, there are some issues to watch for with the Timeline. Here are the essential steps:
- Save the state.
- Enter the symbol.
- Delete the mask layer and rectangle symbol, if present.
- Remove the extra frames and tweens from the symbol layer.
- Break apart the symbol you created and remove it from the library.
- Exit the symbol and adjust the number of frames, if needed.
The first code should be very familiar by now, as you've seen similar things each time. Initialize things and store the state:
fl.enableImmediateUpdates( true );
fl.runScript(fl.configURI + "Effects/shared.jsfl");
var selObj = fl.getDocumentDOM().selection[0];
var tmpTL = fl.getDocumentDOM().getTimeline();
var tmpLayer = tmpTL.layers[ tmpTL.currentLayer ];
var tmpFrame = tmpLayer.frames[ tmpTL.currentFrame ];
var theCurrentFrameNum = tmpFrame.startFrame;
var theCurrentLayer = tmpTL.currentLayer;
Now enter the symbol and get its Timeline:
fl.getDocumentDOM().enterEditMode("inPlace");
var localTL = fl.getDocumentDOM().getTimeline();
var myLayer = 0;
localTL.currentLayer = myLayer;
Delete the mask layer if it is present. You can recognize it
by its name, "MASK." There is no chance of name collision here because you
alone created this Timeline. Remember to set your other
layer to normal because it was being masked before. Get
a reference to the rectangle mask symbol before deleting the layer; that will
make it easy to clean out of the library:
var layerName = localTL.getLayerProperty("name");
if (layerName == "MASK")
{
localTL.setSelectedLayers(0);
localTL.setSelectedFrames([myLayer, 0, 1], true);
// get the mask symbol
var maskItem = fl.getDocumentDOM().selection[0].libraryItem;
localTL.deleteLayer();
localTL.currentLayer = 0;
localTL.setLayerProperty("layerType", "normal");
var maskName = maskItem.name;
fl.getDocumentDOM().library.deleteItem( maskName );
}
Now you have only one layer to worry about. You want to leave one frame here, without a tween:
var fcNum = localTL.layers[myLayer].frameCount;
localTL.setSelectedFrames([myLayer, 0, fcNum], true);
localTL.removeFrames(1, fcNum);
localTL.setSelectedFrames([myLayer, 0, 1], true);
localTL.setFrameProperty('tweenType', 'none', 0);
localTL.currentFrame = 0;
Return the symbol to its original state by breaking it apart. Keep a reference
to it so it is easy to clean out of the library:
fl.getDocumentDOM().selectAll();
var libItem = fl.getDocumentDOM().selection[0].libraryItem;
fl.getDocumentDOM().breakApart();
Remove it from the library. If that was the last symbol in Effects Folder, get rid of the folder too. This should be pretty familiar by now:
// delete the library item
var dom = fl.getDocumentDOM();
var libName = libItem.name;
dom.library.deleteItem( libName );
// delete the folder if it is empty
var folderName = Object.fxutil.getEffectsFolderName();
if (Object.fxutil.folderIsEmpty( folderName ))
{
fl.getDocumentDOM().library.deleteItem( folderName );
}
Exit the symbol:
fl.getDocumentDOM().exitEditMode();
One last thing: Clear out the extra frames added by the effects:
var topTL = fl.getDocumentDOM().getTimeline();
var selectedFrames = topTL.getSelectedFrames();
var removeStart = theCurrentFrameNum + 1;
var removeEnd = theCurrentFrameNum + fl.activeEffect.dur - 2;
topTL.removeFrames(removeStart, removeEnd);
topTL.currentFrame = selectedFrames[1];
fl.getDocumentDOM().selectAll();
var selFrameEnd = selectedFrames[1]+1;
That is all there is to it!
Adding the Editor
The editor for this effect works just like the editor for the Drop Shadow effect. The main difference is that the XML file has all those properties. Even though these are not all used, they are still listed in the XML file, which makes it pretty lengthy. However, they are handled in the exact same way. Here is the list for the Flash object:
<dialog id="transition-dialog" title="Transition">
<flash id="transition_ui" src="transition.swf" width="772" height="456">
<property id="dur" />
<property id="xmode" />
<property id="xpos" />
<property id="ymode" />
<property id="ypos" />
<property id="xscalemode" />
<property id="xscale" />
<property id="yscalemode" />
<property id="yscale" />
<property id="anglemode" />
<property id="angle" />
<property id="colormode" />
<property id="color" />
<property id="easing" />
<property id="direction" />
<property id="changealpha" />
<property id="alpha" />
<property id="fly" />
<property id="fade" />
<property id="wipe" />
<property id="first" />
</flash>
</dialog>
As you can see, it is obvious that more is possible than simple transitions with this code. If you get into making your own effects, it might be handy to split up some of these functions into library files. That way, you can mix and match to create effects, much as sharded.jsfl is used. The editor can be independent of the code—as you see when Transition and Transform use the same code to create different effects—so if you have a series of forward and reverse functions, you can create custom effects very quickly. Seeing as the main reason for using the automation tools in Flash is to save yourself time, it is good to have a system that makes their construction as easy as possible.
That's it for the Transition effect. The next step is to make an effect of your own. There is really good documentation on the JSAPI. Super-neat is the JSFL Live Docs section on macromedia.com, where not only will you find the most up-to-date documentation but you can read comments of others and ask questions about the docs yourself. There is also a JSAPI Help update (flash_jsapi_help.mxp, 1.17 MB) available. Be sure to check out the ExtendFlash mailing list too (a great wealth of knowledge there) and some of the external links for further reading.
Best of luck!
Back: To the beginning
Documentation
- Live Docs
- JSAPI Docs
- Flash JavaScript Dictionary (PDF)
- JSAPI Update (flash_jsapi_help.mxp)
- JavaScript Developer Central (Netscape)
Mailing Lists
- ExtendFlash mailing list (FlashGuru)
External Links
- Introduction to the JSAPI (Guy Watson)
- Extending Flash MX 2004 (Keith Peters)
- XML to UI version 2.2 (Peter Brouwers)